//
//  SearchViewModel.swift
//  shop
//
//  Created by chen on 2025/5/17.
//

import SwiftUI

@MainActor
class SearchViewModel: ObservableObject {
    
    static let shared: SearchViewModel = SearchViewModel()
    
    public init() {}
    
    @Published var hotWord: HotWord = HotWord()
    
    @Published var tags: [String] = []
    
    @Published var suggestion: [String] = []
    
    public func getHotWord(text: Binding<String>) {
        Task{
            let queryParam:[String:Any] = [
                "version": "v1.0.1",
                "type": 1
            ]
            
            await NetManager.shared.httpGet(.hotWord, queryParam: queryParam) { (data: HotWord) in
                self.hotWord = data
                if !data.hotWords.isEmpty {
                    self.getTags()
                    text.wrappedValue = data.hotWords[0]
                }
            }
        }
    }
    
    public func getTags() {
        if hotWord.hotWords.isEmpty {
            tags = []
        } else {
            tags = Array(hotWord.hotWords.shuffled().prefix(35))
        }
    }
    
    public func getSuggestion(keyWords: String) {
        Task{
            let queryParam:[String:Any] = [
                "version": "v1.0.1",
                "keyWords": keyWords,
                "type": 1,
            ]
            
            await NetManager.shared.httpGetList(.suggestion, queryParam: queryParam) { (data:[Suggestion]) in
                if data.isEmpty {
                    self.suggestion = []
                } else {
                    self.suggestion = data.reduce(into: [], { result, item in
                        result.append(item.kw)
                    })
                }
            }
        }
    }
}
